package com.allen.study.config;

import com.alibaba.csp.sentinel.adapter.gateway.common.rule.GatewayFlowRule;
import com.alibaba.csp.sentinel.adapter.gateway.common.rule.GatewayRuleManager;
import com.allen.study.handler.SentinelFallbackHandler;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;

import javax.annotation.PostConstruct;
import java.util.HashSet;
import java.util.Set;

/**
 * @ClassName: GatewaySentinelConfig
 * @Author: AllenSun
 * @Date: 2025/3/15 16:26
 */
@Configuration
public class GatewaySentinelConfig {

    // Sentinel支持自定义异常处理。
    @Bean
    @Order(Ordered.HIGHEST_PRECEDENCE)
    public SentinelFallbackHandler sentinelGatewayExceptionHandler()
    {
        return new SentinelFallbackHandler();
    }

    // @Bean
    // @Order(-1)
    // public GlobalFilter sentinelGatewayFilter()
    // {
    //     return new SentinelGatewayFilter();
    // }

    @PostConstruct
    public void doInit()
    {
        // 加载网关限流规则
        initGatewayRules();
    }

    /**
     * 网关限流规则
     */
    private void initGatewayRules()
    {
        Set<GatewayFlowRule> rules = new HashSet<>();
        // 测试验证，一分钟内访问三次系统服务出现异常提示表示限流成功。
        rules.add(new GatewayFlowRule("allen-study-module")
                .setCount(3) // 限流阈值
                .setIntervalSec(10)); // 统计时间窗口，单位是秒，默认是 1 秒
        // 可以配置多个
        rules.add(new GatewayFlowRule("allen_camunda")
                .setCount(3) // 限流阈值
                .setIntervalSec(10));
        // 加载网关限流规则
        GatewayRuleManager.loadRules(rules);
    }
}
